<template>
  <el-menu-item index="8" @click="dialogVisible = true"> 路况信息 </el-menu-item>
  <el-dialog
    v-model="dialogVisible"
    title="路况信息详情"
    width="1500"
    custom-class="traffic-dialog"
  >
    <div class="search-container">
      <el-input
        v-model="searchKey"
        placeholder="请输入关键词搜索"
        :prefix-icon="Search"
        clearable
      />
    </div>
    <el-table :data="filteredData" height="500" border stripe header-row-class-name="custom-header">
      <el-table-column prop="reportByWho" label="提交用户" width="120" align="center" />
      <el-table-column prop="eventType" label="事件类型" width="150" align="center" />
      <el-table-column prop="eventAddress" label="事件地址" width="180" align="center" />
      <el-table-column prop="nearbyBuilding" label="附近建筑" width="150" align="center" />
      <el-table-column prop="occurrenceTime" label="发生时间" width="180" align="center" />
      <el-table-column prop="eventDescription" label="事件描述" min-width="200" align="center" />
      <el-table-column prop="eventPhoto" label="现场照片" min-width="200" align="center">
        <template #default="{ row }">
          <img :src="row.eventPhoto" class="traffic-photo" alt="现场照片" />
        </template>
      </el-table-column>
      <el-table-column prop="auditStatus" label="处理状态" width="120" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.auditStatus === 'approved'" type="primary"> 已通过 </el-tag>
          <el-tag v-else-if="row.auditStatus === 'rejected'" type="info"> 已忽略 </el-tag>
          <span v-else class="audit-btns">
            <el-tag type="success" @click="handleEvent(row, 'approved')"> 通过</el-tag>
            <el-tag type="danger" @click="handleEvent(row, 'rejectd')"> 忽略</el-tag>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const dialogVisible = ref(false)
const tableData = ref([]) // 表格数据
const searchKey = ref('') // 搜索关键词

const fetchReports = async () => {
  try {
    const { data } = await axios.post('http://localhost:3001/getreport', { str: '' })
    // 检查后端返回的状态码
    if (data.data.status === 1) {
      const reports = Array.isArray(data.data.data) ? data.data.data : [data.data.data]
      tableData.value = reports.map((report) => ({
        ...report,
        occurrenceTime: new Date(report.occurrenceTime).toLocaleString(), // 转成中国时间
      }))
    } else {
      console.error('未找到路况信息:', data.data.message)
    }
  } catch (error) {
    if (error.response) {
      console.error('请求错误:', error.response.data.error)
    } else {
      console.error('请求失败:', error.message)
    }
  }
}
onMounted(fetchReports)

// 过滤后的数据
const filteredData = computed(() => {
  const key = searchKey.value.split(/\s+/).filter(Boolean)
  return key.length
    ? tableData.value.filter((item) =>
        key.every(
          (k) =>
            item.reportByWho.includes(k) ||
            item.eventType.includes(k) ||
            item.eventAddress.includes(k) ||
            item.nearbyBuilding.includes(k) ||
            item.eventDescription.includes(k),
        ),
      )
    : tableData.value
})

const handleEvent = async (row, type) => {
  ElMessageBox.confirm(`请确认审核结果为：${type === 'approved' ? '通过' : '忽略'}`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 根据操作类型设置状态值
        const status = type === 'approved' ? 'approved' : 'rejected'
        console.log({ id: row.id, status: status })
        const token = localStorage.getItem('token')
        const response = await axios.post(
          'http://localhost:3001/updatereportstatus',
          { id: row.id, status: status },
          { headers: { Authorization: `Bearer ${token}` } },
        )
        if (response.status === 200) {
          ElMessage.success('完成审核')
        }
        await fetchReports()
      } catch (error) {
        let errorMessage = '状态更新失败'
        if (error.response) {
          errorMessage = error.response.data?.error || error.response.data?.message || errorMessage
        } else if (error.request) {
          errorMessage = '服务器未响应，请检查网络连接'
        }
        ElMessage.error(errorMessage)
      }
    })
    .catch(() => {
      ElMessage.info('已取消审核')
    })
}
</script>

<style lang="scss" scoped>
.search-container {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;

  .el-input {
    width: 240px;
  }
}

// 表格样式优化
:deep(.custom-header) {
  th {
    background-color: #f8f9fa;
    color: #606266;
    font-weight: 600;
  }
}

.el-table {
  img {
    max-width: 250px;
    max-height: 120px;
    object-fit: cover;
  }
  .audit-btns {
    display: flex;
    gap: 10px;
    cursor: pointer;
  }
}
</style>
